#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库工厂类 - 统一管理数据库连接和Repository实例
"""

import logging
from typing import Optional
from database.connect_sqlserver import SQLServerConnection
from config.config import DATABASE_CONFIG
from .zbfx_repository import ZbfxRepository
from .mnjt_repository import MnjtRepository


class DatabaseFactory:
    """数据库工厂类，提供统一的数据库连接和Repository管理"""
    
    _instance = None
    _connection = None
    _zbfx_repo = None
    _mnjt_repo = None
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super(DatabaseFactory, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        """初始化数据库工厂"""
        if self._initialized:
            return
            
        self.logger = logging.getLogger(__name__)
        self.config = DATABASE_CONFIG
        self._initialized = True
        
        # 初始化数据库连接
        self._initialize_connection()
    
    def _initialize_connection(self):
        """初始化数据库连接"""
        try:
            # 解析服务器和端口
            server_parts = self.config['server'].split(',')
            server = server_parts[0]
            port = int(server_parts[1]) if len(server_parts) > 1 else 1433
            
            # 创建数据库连接
            self._connection = SQLServerConnection(
                server=server,
                port=port,
                database=self.config['database'],
                username=self.config['username'],
                password=self.config['password']
            )
            
            # 尝试连接
            self.logger.info("尝试连接数据库...")
            connected = self._connection.connect()
            
            if connected:
                self.logger.info("数据库连接成功")
                # 测试连接
                if not self._connection.test_connection():
                    self.logger.warning("数据库连接测试失败")
            else:
                self.logger.error("数据库连接失败")
                raise Exception("无法连接到数据库")
                
        except Exception as e:
            self.logger.error(f"数据库初始化失败: {e}")
            raise
    
    def get_connection(self) -> SQLServerConnection:
        """
        获取数据库连接
        
        Returns:
            SQLServerConnection: 数据库连接对象
        """
        if not self._connection:
            self._initialize_connection()
        return self._connection
    
    def get_zbfx_repository(self) -> ZbfxRepository:
        """
        获取Zbfx表Repository实例
        
        Returns:
            ZbfxRepository: Zbfx表数据访问对象
        """
        if not self._zbfx_repo:
            connection = self.get_connection()
            self._zbfx_repo = ZbfxRepository(connection)
            self.logger.debug("创建ZbfxRepository实例")
        
        return self._zbfx_repo
    
    def get_mnjt_repository(self) -> MnjtRepository:
        """
        获取Mnjt表Repository实例
        
        Returns:
            MnjtRepository: Mnjt表数据访问对象
        """
        if not self._mnjt_repo:
            connection = self.get_connection()
            self._mnjt_repo = MnjtRepository(connection)
            self.logger.debug("创建MnjtRepository实例")
        
        return self._mnjt_repo
    
    def validate_all_connections(self) -> bool:
        """
        验证所有数据库连接
        
        Returns:
            bool: 所有连接是否有效
        """
        try:
            # 验证主连接
            if not self._connection or not self._connection.test_connection():
                return False
            
            # 验证Repository连接
            zbfx_repo = self.get_zbfx_repository()
            mnjt_repo = self.get_mnjt_repository()
            
            return (zbfx_repo.validate_connection() and 
                   mnjt_repo.validate_connection())
                   
        except Exception as e:
            self.logger.error(f"连接验证失败: {e}")
            return False
    
    def get_database_info(self) -> dict:
        """
        获取数据库基本信息
        
        Returns:
            dict: 数据库信息
        """
        try:
            zbfx_repo = self.get_zbfx_repository()
            mnjt_repo = self.get_mnjt_repository()
            
            zbfx_info = zbfx_repo.get_table_info('zbfx')
            mnjt_info = mnjt_repo.get_table_info('mnjt')
            
            return {
                'zbfx_table': zbfx_info,
                'mnjt_table': mnjt_info,
                'connection_status': 'connected' if self.validate_all_connections() else 'disconnected'
            }
            
        except Exception as e:
            self.logger.error(f"获取数据库信息失败: {e}")
            return {'error': str(e)}
    
    def close_all_connections(self):
        """关闭所有数据库连接"""
        try:
            if self._connection:
                self._connection.close()
                self.logger.info("数据库连接已关闭")
            
            # 重置Repository实例
            self._zbfx_repo = None
            self._mnjt_repo = None
            self._connection = None
            
        except Exception as e:
            self.logger.error(f"关闭数据库连接失败: {e}")
    
    def reconnect(self):
        """重新连接数据库"""
        self.logger.info("重新连接数据库...")
        self.close_all_connections()
        self._initialize_connection()
    
    @classmethod
    def reset_instance(cls):
        """重置单例实例（主要用于测试）"""
        if cls._instance:
            cls._instance.close_all_connections()
        cls._instance = None
        cls._connection = None
        cls._zbfx_repo = None
        cls._mnjt_repo = None


# 全局工厂实例
database_factory = DatabaseFactory()
